<template>
  <img v-show="!!captchaSrc" :src="captchaSrc" alt="验证码" @click="onload()"/>
</template>

<script setup>
import {ref, watch} from 'vue';
import store from '@/store';

const props = defineProps({interval: Boolean})
// 定时刷新验证码
let timer = null
// 点击刷新验证码节流
let clickTimer = null

// 验证码图片地址
const captchaSrc = ref();
let captchaToken = ref(store.state.captchaToken)
// 加载图形验证码
const loadCaptcha = () => {
  captchaToken = Tool.uuid(10)
  store.commit('refreshCaptchaToken', captchaToken)
  captchaSrc.value = `${process.env.VUE_APP_BASE_API}/business/captcha/get/order_${captchaToken}`
};

function onload() {
  // 节流
  if (!clickTimer) {
    clickTimer = setTimeout(() => {
      loadCaptcha()
      clickTimer = null;
    }, 1000);
  }
}

watch(() => props.interval, val => {
  if (val) {
    loadCaptcha()
    // 每30秒刷新一次验证码
    timer = setInterval(() => {
      loadCaptcha()
    }, 30000)
  } else {
    timer && clearInterval(timer)
  }
}, {immediate: true})
</script>
